package com.ynyr.jar.wss.controller;

import com.ynyr.jar.common.util.StringUtil;
import com.ynyr.jar.wss.entity.WssEUser;
import com.ynyr.jar.wss.service.IWssEUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
@RequestMapping("/")
public class IndexViewController {

    private final IWssEUserService userService;

    private final BCryptPasswordEncoder passwordEncoder;

    public IndexViewController(IWssEUserService userService, BCryptPasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping("/reg")
    public String registry() {
        return "reg";
    }

    @PostMapping("/reg")
    public String reg(Model model, String username, String password, String confirmPassword) {
        WssEUser user = new WssEUser();

        if(!password.equals(confirmPassword)) {
            model.addAttribute("error", "确认密码不正确");
            return "reg";
        }

        try {
            user.setWssEUserId(StringUtil.uuid());
            user.setUsername(username);
            user.setPassword(passwordEncoder.encode(password));
            userService.save(user);
            model.addAttribute("message", "注册成功");
            return "message";
        } catch (Exception e) {
            log.info(ExceptionUtils.getStackTrace(e));
            model.addAttribute("error", "注册失败, " + e.getMessage());
            return "reg";
        }
    }

    @GetMapping("/login")
    public String loginView(HttpServletRequest request, Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(!(authentication instanceof AnonymousAuthenticationToken)) {
            return "redirect:chat";
        }


        boolean isError = "".equals(request.getParameter("error"));

        if(isError) {
            model.addAttribute("error", "用户名或者密码错误");
            return "login";
        }

        boolean isLogout = "".equals(request.getParameter("logout"));

        if(isLogout) {
            model.addAttribute("message", "注销成功");
            return "message";
        }

        return "login";
    }

    @RequestMapping("chat")
    public String chat() {
        return "chat";
    }
}
